<template>
  <div class="container">
    <!-- 顶部导航条 -->
    <van-nav-bar left-arrow @click-left="$router.back()" title="编辑资料"></van-nav-bar>
    <van-cell-group>
      <van-cell is-link title="头像" @click="hShowImage" center>
        <van-image
          slot="default"
          width="1.5rem"
          height="1.5rem"
          fit="cover"
          round
          :src="user.photo"
        />
      </van-cell>
      <!-- 用来选择本地文件 -->
      <input type="file" hidden @change="hPhotoChange" ref="refPhoto" />
      <van-cell is-link title="名称" :value="user.name" @click="showName=true"/>
      <van-cell is-link title="性别" :value="user.gender === 0?'男':'女'" @click="showGender=true"/>
      <van-cell is-link title="生日" :value="user.birthday" @click="showBirthday=true"/>
    </van-cell-group>
    <!-- 修改名字 -->
    <van-dialog @confirm="hSaveName" v-model="showName" title="修改名字" show-cancel-button>
      <van-field type="text" focus v-model="newName" placeholder="请输入名字" />
    </van-dialog>
    <!-- /修改名字 -->
    <!-- 修改性别 -->
    <van-action-sheet
      v-model="showGender"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="hChangeGender"
      @cancel="showGender=false"
    />
    <!-- <van-popup v-model="showGender" position="bottom">
      <van-nav-bar
          title="修改性别"
          left-text="取消"
          @click-left="showGender=false"
      >
      </van-nav-bar>

      <van-cell is-link title="男" @click="hChangeGender(0)" />
      <van-cell is-link title="女" @click="hChangeGender(1)" />
    </van-popup> -->
    <!-- /修改性别 -->
    <!-- 修改生日 -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="newDate"
        type="date"
        title="修改生日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="hSaveBirthday"
        @cancel="showBirthday=false"
      />
    </van-popup>
    <!-- /修改生日 -->
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { userGetInfo, updateUserInfo, updatePhoto } from '@/api/user.js';
export default {
  name: 'userProfile',
  data () {
    return {
      // 控制弹层
      showName: false,
      showGender: false,
      showBirthday: false,

      // 当前用户的信息
      user: {},
      actions: [{ name: '男' }, { name: '女' }],
      // 修改后的新名字
      newName: '',
      // 修改后新生日
      newDate: new Date(),
      minDate: new Date(1965, 0, 10), // dateTime-picker中最小时间
      maxDate: new Date() // 当前时间
    };
  },
  created () {
    this.loadUserProfile();
  },
  methods: {
    hShowImage () {
      // 点击头像调出选择文件的input
      this.$refs.refPhoto.click();
    },
    async hPhotoChange () {
      try {
        console.log('表示用户选中某个文件');
        // 1.获取用户选中的图片文件
        // this.$refs.refPhoto用来获取<input type="file"的引用
        // .files[0]  files是input的一个属性，用来保存用户选中的文件
        const file = this.$refs.refPhoto.files[0];
        if (!file) return;
        // 2.调用接口上传文件
        // 采用FormData对象来包装参数(参数类型：file)
        const fd = new FormData();
        fd.append('photo', file);
        const result = await updatePhoto(fd);
        console.log('上传头像', result);
        // 3.更新视图
        this.user.photo = result.data.data.photo;
        // 4.保存头像地址到vuex
        this.$store.commit('mSetPhoto', this.user.photo);
        this.$toast.success('修改头像成功');
      } catch (error) {
        console.log(error.message);
      }
    },
    async hSaveBirthday () {
      const birthday = dayjs(this.newDate).format('YYYY-MM-DD');
      try {
        await updateUserInfo({
          birthday
        });
        this.user.birthday = birthday;
        this.showBirthday = false;
      } catch (error) {
        console.log(error);
      }
    },
    async hChangeGender (val1, val2) {
      console.log('性别', val1, val2);
      const gender = val1.name === '男' ? 0 : 1;
      try {
        await updateUserInfo({
          gender
        });
        this.user.gender = gender;
        this.showGender = false;
      } catch (error) {
        console.log(error);
      }
    },
    async hSaveName () {
      // 保存名字
      // 1.判断是否为空
      if (!this.newName) {
        // todo：如果是验证不通过，就不要关闭弹层
        // this.showName = true;
        this.$toast.fail('名字不能为空');
        return;
      }
      if (this.newName === this.user.name) return;
      try {
        // 2.修改
        const result = await updateUserInfo({
          name: this.newName
        });
        // 3.更新视图
        this.user.name = this.newName;
        console.log(result);
        this.newName = '';
      } catch (error) {
        // 需要根据error的具体提示，来给用户不同的提示，长度，重名等等
        this.$toast.fail(error.message);
      }
    },
    async loadUserProfile () {
      const result = await userGetInfo();
      this.user = result.data.data;
      // 设置初始值
      this.newName = this.user.name;
    }
  }
};
</script>

<style lang="less">
.van-nav-bar__text{
  color:#fff;
}
</style>
